// 2025/11/13
// 二叉树的最近公共祖先

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == nullptr || root == p || root == q) 
            return root;
        
        TreeNode* l = lowestCommonAncestor(root->left, p, q);
        TreeNode* r = lowestCommonAncestor(root->right, p, q);
        if(!l && !r) return nullptr;
        else if(!l) return r;
        else if(!r) return l;
        else
        {
            if((l == p && r == q) || (l == q && r == p))
                return root;
            else if(l == root->left)
                return root->left;
            else if(r == root->right)
                return root->right;
            else
                return nullptr;
        }
    }
};